package de.tewdreyer.android.erc;

import java.io.File;
import java.util.Date;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class UploadPhoto extends Activity {
	/**
	 * an onclicklistener for getting an intent to the phone's
	 * integrated camera application
	 * @see android.view.View.OnClickListener
	 */
	private class CameraOnClickListener implements OnClickListener {
		/**
		 * @param view view that has been clicked
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		@Override
		public void onClick(View view) {
			Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePhoto, TAKE_PHOTO);			
		}
	}
	
	/**
	 * an onclicklistener for getting an intent to the phone's
	 * integrated gallery application
	 * @see android.view.View.OnClickListener
	 */
	private class GalleryOnClickListener implements OnClickListener {
		/**
		 * @param view view that has been clicked
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		@Override
		public void onClick(View view) {
			Intent pickPhoto = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(pickPhoto, PICK_PHOTO);
		}
	}
	
	/**
	 * an onclicklistener for uploading a photo
	 * @see android.view.View.OnClickListener
	 */
	private class UploadOnClickListener implements OnClickListener {
		/**
		 * @param view view that has been clicked
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		@Override
        public void onClick(View view){
        	// notify user
            Toast.makeText(getApplicationContext(), "trying to post ..", Toast.LENGTH_SHORT).show();
        	
        	//no photo selected
            if(photoUri == null){
                Toast.makeText(getApplicationContext(),"no photo selected",Toast.LENGTH_SHORT).show();
                return;
            }

            // test if deviceIdentifier is set
            if(ERC.deviceIdentifier == null){
                Toast.makeText(getApplicationContext(),"no device selected ..",Toast.LENGTH_SHORT).show();
                return;
            }

            String fileComment;
            Date now = new Date(System.currentTimeMillis());
            if(edTxtDescription.getText().length() != 0){
                fileComment = edTxtDescription.getText().toString();
            } else {
                fileComment = DateFormat.format("dd-MM-yyyy hh:mm:ss",now) + " uploaded by android phone";
            }

            // photo selected
            MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            FileBody file = new FileBody(new File(convertUri2Path(photoUri)));

            me.addPart("filepath",file);
            me.addPart("filecomment", HttpPoster.createStringBody(fileComment));
            me.addPart("createlink",HttpPoster.createStringBody("on"));

            HttpPoster poster = new HttpPoster(ERC.uploadPhotoUrl + ERC.deviceIdentifier, me);

            // perform POST
            int returnCode = poster.performPost();
            if(returnCode != poster.ErrorCode()){                    
                if(returnCode >= 200 && returnCode < 400){
                    // notify user
                    Toast.makeText(getApplicationContext(),"http POST successful",Toast.LENGTH_SHORT).show();

                    // reset image view, text box and url
                    imgVwPhoto.setImageBitmap(null);
                    edTxtDescription.setText("");
                    photoUri = null;
                } else {
                    Toast.makeText(getApplicationContext(),"http POST failed",Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getApplicationContext(),"http POST failed",Toast.LENGTH_SHORT).show();
            }
        }
	}
	
	private Button    btnTakePhoto;
	private Button    btnPickFromGallery;
	private Button    btnUpload;
	private EditText  edTxtDescription;
	private ImageView imgVwPhoto;
	
    private Uri       photoUri = null;
    private Bitmap    photo = null;

    private final int TAKE_PHOTO = 0;
    private final int PICK_PHOTO = 1;

    /**
     * @param inState activity's previous state 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle inState) {
        super.onCreate(inState);

        setContentView(R.layout.upload_photo);

        btnTakePhoto = (Button)findViewById(R.id.btnTakePhoto);
        btnPickFromGallery = (Button)findViewById(R.id.btnPickFromGallery);
        btnUpload = (Button)findViewById(R.id.btnUpload);
        edTxtDescription = (EditText)findViewById(R.id.edtTxtPhtDscrptn);
        imgVwPhoto = (ImageView)findViewById(R.id.imgVwPhoto);
        
        // set OnClickListener for button takePhoto
        btnTakePhoto.setOnClickListener(new CameraOnClickListener());
        
        // set OnClickListener for button pick from gallery
        btnPickFromGallery.setOnClickListener(new GalleryOnClickListener());

        // set OnClickListener for button upload
        btnUpload.setOnClickListener(new UploadOnClickListener());
    }

    /**
     * 
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent result){
    	switch(requestCode){
    	case TAKE_PHOTO:
    	case PICK_PHOTO:
    		if(resultCode == Activity.RESULT_OK){
    			photoUri = result.getData();
    			photo = uri2bitmap(photoUri);
    			imgVwPhoto.setImageBitmap(photo);
    		}
    		break;
    	}
    }

	/**
	 * 
	 */
    @Override
    public void onSaveInstanceState(Bundle outState){
        if(photoUri != null){
            outState.putString("photoUri",photoUri.toString());
        }
        super.onSaveInstanceState(outState);
    }

    /**
     * 
     */
    @Override
    public void onRestoreInstanceState(Bundle inState){
        super.onRestoreInstanceState(inState);
        String savedPhotoUri = inState.getString("photoUri");
        if(savedPhotoUri != null){
             photoUri = Uri.parse(inState.getString("photoUri"));
             photo = uri2bitmap(photoUri);
             imgVwPhoto.setImageBitmap(photo);
        }
    }
    
    /**
     * free memory allocated for photo
     * @see android.app.Activity##onDestroy()
     */
    @Override
    public void onDestroy(){
    	super.onDestroy();
    	if(photo != null)
    		photo.recycle();
    	photo = null;
    }

    /**
     * convert an android media uri to a bitmap
     * @param uri
     * @return Bitmap a to screen size scaled down bitmap 
     */
    private Bitmap uri2bitmap(Uri uri) {
		Display d = getWindowManager().getDefaultDisplay();
		return scaleDown(uri, d.getHeight(),d.getWidth());
	}
    
    private String convertUri2Path(Uri uri){
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private Bitmap scaleDown(Uri uri, int tgtHeight, int tgtWidth){
        Options inOptions = new Options();
        inOptions.inJustDecodeBounds = true;
    	BitmapFactory.decodeFile(convertUri2Path(uri),inOptions);

        int srcHeight = inOptions.outHeight;
        int srcWidth = inOptions.outWidth;
        int scale = 1;
        while(srcHeight / 2 > tgtHeight && srcWidth / 2 > tgtWidth){
            srcHeight /= 2;
            srcWidth /= 2;
            scale *= 2;
        }

        Options outOptions = new Options();
        outOptions.inSampleSize = scale;

        return BitmapFactory.decodeFile(convertUri2Path(uri),outOptions);
    }
}

